package ex.app.system.service;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.RowMapper;

import com.fzy.core.BaseService;
import com.fzy.core.acegi.UserDetailsImpl;
import com.fzy.core.utils.CollectionUtils;
import com.fzy.core.utils.RsUtils;
import com.fzy.core.utils.StringUtils;
import com.fzy.core.utils.U;

public class LoginService extends BaseService {

	private static final Logger log = LoggerFactory.getLogger(LoginService.class);
	
	public List getRecruitRoles(){
		String sql = "select roleid id,rolename name,roledesc title from auth_rolemsg where roleid in (40, 41, 42, 43, 44, 45, 48)";
		return this.queryForList(sql);
	}
	
	
	public UserDetailsImpl getInsideUser(String grpCode,String loginName){
		List roles = getRecruitRoles();
		List roleIds = U.getIdList(roles);
		String roleIdsString = CollectionUtils.join(roleIds);
		
		String sql1 = "select ur.userid, r.roleid, r.rolename, r.roledesc from auth_userrolerel ur left join auth_rolemsg r on ur.roleid = r.roleid where r.roleid in ("+roleIdsString+")";
		final List userRoleRelations = queryForList(sql1);
		
		String sql = "";
		sql += " SELECT   a.userid,";
		sql += "          a.empid,";
		sql += "          a.grpid,";
		sql += "          a.loginname,";
		sql += "          a.passwd,";
		sql += "          b.grpcode,";
		sql += "          e.empname";
		sql += "   FROM auth_usermsg a";
		sql += "             LEFT JOIN";
		sql += "                auth_grprel b";
		sql += "             ON b.grpid = a.grpid";
		sql += "          LEFT JOIN";
		sql += "             auth_emply e";
		sql += "          ON a.empid = e.empid";
		sql += " WHERE   EXISTS";
		sql += "            (SELECT   *";
		sql += "               FROM      auth_userrolerel ur";
		sql += "                      LEFT JOIN";
		sql += "                         auth_rolemsg r";
		sql += "                      ON ur.roleid = r.roleid";
		sql += "              WHERE       ur.userid = a.userid";
		sql += "                      AND r.roleid in ("+roleIdsString+"))";
		sql += "         AND workflg = '0' and b.grpcode=? and a.loginname=? and rownum=1" ;
		String params[]=new String[2];
		params[0]=grpCode;
		params[1]=loginName;
		//List result = query(sql, params,new MyMapRow());
		
		List result = query(sql, params,
				new RowMapper() {
					public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
						UserDetailsImpl d = new UserDetailsImpl();
						d.setId(RsUtils.getLong("userid", rs));
						// id as username
						d.setUsername(StringUtils.defaultString(d.getId()));
						d.setLoginName(rs.getString("loginname"));
						d.setGroupId(RsUtils.getLong("grpid", rs));
						d.setEmployeeId(RsUtils.getLong("empid", rs));
						d.setPassword(rs.getString("passwd"));
						d.setEmployeeName(rs.getString("empname"));
						d.setGroupCode(rs.getString("grpcode"));
						d.setVuserFlag("0");
						
						for (Iterator iterator = userRoleRelations.iterator(); iterator
								.hasNext();) {
							Map m = (Map) iterator.next();
							BigDecimal userid = (BigDecimal)m.get("userid");
							if(userid != null && userid.longValue() == d.getId().longValue() && m.get("rolename") != null){
								GrantedAuthority[] as = d.getAuthorities();
								List alist = new ArrayList();
								if(as != null && as.length > 0)
									CollectionUtils.addAll(alist, as);
								GrantedAuthority g = new GrantedAuthorityImpl((String)m.get("rolename"));
								alist.add(g);
								GrantedAuthority[] asNew = new GrantedAuthority[alist.size()];
								for(int i = 0; i < alist.size(); i++){
									asNew[i] = (GrantedAuthority)alist.get(i);
								}
								d.setAuthorities(asNew);
							}
						}
						return d;
					}
				});
		return result.size()==0?null:(UserDetailsImpl)result.get(0);
	}
	
	
	public class MyMapRow implements RowMapper {
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			UserDetailsImpl d = new UserDetailsImpl();
			d.setId(RsUtils.getLong("userid", rs));
			// id as username
			d.setUsername(StringUtils.defaultString(d.getId()));
			d.setLoginName(rs.getString("loginname"));
			d.setGroupId(RsUtils.getLong("grpid", rs));
			d.setEmployeeId(RsUtils.getLong("empid", rs));
			d.setPassword(rs.getString("passwd"));
			d.setEmployeeName(rs.getString("empname"));
			d.setGroupCode(rs.getString("grpcode"));
			d.setVuserFlag("0");	
			
			return d;
		}
	}
	
	
	public UserDetailsImpl getInsideUser(String userId){
		List roles = getRecruitRoles();
		List roleIds = U.getIdList(roles);
		String roleIdsString = CollectionUtils.join(roleIds);
		
		String sql1 = "select ur.userid, r.roleid, r.rolename, r.roledesc from auth_userrolerel ur left join auth_rolemsg r on ur.roleid = r.roleid where r.roleid in ("+roleIdsString+")";
		final List userRoleRelations = queryForList(sql1);
		
		String sql = "";
		sql += " SELECT   a.userid,";
		sql += "          a.empid,";
		sql += "          a.grpid,";
		sql += "          a.loginname,";
		sql += "          a.passwd,";
		sql += "          b.grpcode,";
		sql += "          e.empname";
		sql += "   FROM auth_usermsg a";
		sql += "             LEFT JOIN";
		sql += "                auth_grprel b";
		sql += "             ON b.grpid = a.grpid";
		sql += "          LEFT JOIN";
		sql += "             auth_emply e";
		sql += "          ON a.empid = e.empid";
		sql += " WHERE   EXISTS";
		sql += "            (SELECT   *";
		sql += "               FROM      auth_userrolerel ur";
		sql += "                      LEFT JOIN";
		sql += "                         auth_rolemsg r";
		sql += "                      ON ur.roleid = r.roleid";
		sql += "              WHERE       ur.userid = a.userid";
		sql += "                      AND r.roleid in ("+roleIdsString+"))";
		sql += "         AND workflg = '0'  and a.userid=? and rownum=1" ;
		Long params[]=new Long[1];
		params[0]=new Long(userId);
		 
		List result = query(sql, params,
				new RowMapper() {
					public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
						UserDetailsImpl d = new UserDetailsImpl();
						d.setId(RsUtils.getLong("userid", rs));
						// id as username
						d.setUsername(StringUtils.defaultString(d.getId()));
						d.setLoginName(rs.getString("loginname"));
						d.setGroupId(RsUtils.getLong("grpid", rs));
						d.setEmployeeId(RsUtils.getLong("empid", rs));
						d.setPassword(rs.getString("passwd"));
						d.setEmployeeName(rs.getString("empname"));
						d.setGroupCode(rs.getString("grpcode"));
						d.setVuserFlag("0");
						
						for (Iterator iterator = userRoleRelations.iterator(); iterator
								.hasNext();) {
							Map m = (Map) iterator.next();
							BigDecimal userid = (BigDecimal)m.get("userid");
							if(userid != null && userid.longValue() == d.getId().longValue() && m.get("rolename") != null){
								GrantedAuthority[] as = d.getAuthorities();
								List alist = new ArrayList();
								if(as != null && as.length > 0)
									CollectionUtils.addAll(alist, as);
								GrantedAuthority g = new GrantedAuthorityImpl((String)m.get("rolename"));
								alist.add(g);
								GrantedAuthority[] asNew = new GrantedAuthority[alist.size()];
								for(int i = 0; i < alist.size(); i++){
									asNew[i] = (GrantedAuthority)alist.get(i);
								}
								d.setAuthorities(asNew);
							}
						}
						return d;
					}
				});
		return result.size()==0?null:(UserDetailsImpl)result.get(0);
	}
	
	public UserDetailsImpl getOutsideUser(String loginName){
		String sql1 = "select  r.roleid, r.rolename, r.roledesc from  auth_rolemsg r where r.roleid =49";
		final List userRole = queryForList(sql1);
		
		String sql="select vusername loginname,nmemusrid userid,0 grpid,0 empid,vpasswd passwd,vrealname empname,'0' grpcode from ms_auth_memusr_new a where vusername=?  and rownum=1";
		String params[]=new String[1];
		params[0]=loginName;
		
		List result = query(sql, params,
				new RowMapper() {
					public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
						UserDetailsImpl d = new UserDetailsImpl();
						d.setId(RsUtils.getLong("userid", rs));
						// id as username
						d.setUsername(StringUtils.defaultString(d.getId()));
						d.setLoginName(rs.getString("loginname"));
						d.setGroupId(RsUtils.getLong("grpid", rs));
						d.setEmployeeId(RsUtils.getLong("empid", rs));
						d.setPassword(rs.getString("passwd"));
						d.setEmployeeName(rs.getString("empname"));
						d.setGroupCode(rs.getString("grpcode"));
						d.setVuserFlag("1");
						for (Iterator iterator = userRole.iterator(); iterator
								.hasNext();) {
							Map m = (Map) iterator.next();
							BigDecimal userid = (BigDecimal)m.get("userid");
							if(m.get("rolename") != null){
								GrantedAuthority[] as = d.getAuthorities();
								List alist = new ArrayList();
								if(as != null && as.length > 0)
									CollectionUtils.addAll(alist, as);
								GrantedAuthority g = new GrantedAuthorityImpl((String)m.get("rolename"));
								alist.add(g);
								GrantedAuthority[] asNew = new GrantedAuthority[alist.size()];
								for(int i = 0; i < alist.size(); i++){
									asNew[i] = (GrantedAuthority)alist.get(i);
								}
								d.setAuthorities(asNew);
							}
						}
						return d;
					}
				});
		return result.size()==0?null:(UserDetailsImpl)result.get(0);
	}
	
	
	
	
}
